package ee.ut.re;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;


import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import ee.ut.re.PricePredictor.Stats;

public class WebMain {
  public static void main(String[] args) throws IOException {
    InetSocketAddress addr = new InetSocketAddress(8080);
    HttpServer server = HttpServer.create(addr, 0);

    server.createContext("/", new MainHandler());
    server.createContext("/submit", new SubmitHandler());
    server.setExecutor(Executors.newCachedThreadPool());
    server.start();
    System.out.println("Server is listening on port 8080" );
  }
}



class SubmitHandler implements HttpHandler {

	PricePredictor model = new PricePredictor();
	
	public SubmitHandler() throws IOException {
		FlatStream flatStream = new FlatStream(new File("/tmp/city2.sql"));
		
		Collection<Flat> flats = new ArrayList<Flat>();
		int totalSize = Integer.MAX_VALUE;
		try {
			while(flatStream.hasNext() && flats.size() < totalSize  ) {
				Flat flat = flatStream.next();
				flats.add(flat);
			}} catch (Exception x) {	
		}
		model.setKnownFlats(flats);
		
	}
	
	public void handle(HttpExchange exchange) throws IOException {
		URI uri = exchange.getRequestURI();
		
		Flat flat = flat(uri);
		
		Headers responseHeaders = exchange.getResponseHeaders();
	      responseHeaders.set("Content-Type", "text/html");
	      exchange.sendResponseHeaders(200, 0);
	     
	      
	      OutputStream responseBody = exchange.getResponseBody();
	      
	      try {
			Stats stats = model.predict(flat, kVal(uri));
			responseBody.write(stats.toString().getBytes("UTF-8"));
		} catch (Exception e) {
			responseBody.write(e.toString().getBytes("UTF-8"));
			e.printStackTrace();
		}
	      responseBody.close();
		
	}

	private int kVal(URI uri) {
		String[] parts = uri.getQuery().split("&");
		Map<String, String> vals = new HashMap<String,String>();
		
		for (String p : parts) {
			String[] kv = p.split("=");
			vals.put(kv[0], kv[1]);
		}
		
		return Integer.valueOf(vals.get("k"));
	}
	
	private Flat flat(URI uri) {
		String[] parts = uri.getQuery().split("&");
		Map<String, String> vals = new HashMap<String,String>();
		
		for (String p : parts) {
			String[] kv = p.split("=");
			vals.put(kv[0], kv[1]);
		}
		
		Date salesDate = new Date();
		salesDate.setYear(111);
		salesDate.setMonth(10); //November, we dont have index data from December 2011
		return new Flat(0.0, 0, 
				vals.containsKey("saun"), vals.containsKey("rodu"), vals.get("linnaosa"), 
				salesDate, 0.0, "1,1", vals.containsKey("keskkyte"), vals.containsKey("gaaskyte"), vals.containsKey("elkkyte"), 
				vals.containsKey("ahjukyte"), vals.containsKey("garaazh"), vals.containsKey("kamin"));
		
		
	}
	
}

class MainHandler implements HttpHandler {
	
	static String html = 
			"<html><h1>Flat Price Predictor</h1>" +
			"<form method=\"get\" action=\"submit\">" +
					"<input type=\"checkbox\" name=\"saun\" value=\"true\" />Saun<br />" +
					"<input type=\"checkbox\" name=\"rodu\" value=\"true\" />Rodu<br />" +
					"<input type=\"checkbox\" name=\"keskkyte\" value=\"true\" />keskkyte<br />" +
					"<input type=\"checkbox\" name=\"gaaskyte\" value=\"true\" />gaaskyte<br />" +
					"<input type=\"checkbox\" name=\"elkkyte\" value=\"true\" />elkkyte<br />" +
					"<input type=\"checkbox\" name=\"ahjukyte\" value=\"true\" />ahjukyte<br />" +
					"<input type=\"checkbox\" name=\"kamin\" value=\"true\" />kamin<br />" +
					"<input type=\"checkbox\" name=\"garaazh\" value=\"true\" />garaazh<br />" +
					"<select name=\"linnaosa\">" +
					"<option value=\"Kesklinn\">Kesklinn</option>" +
					"<option value=\"Vanalinn\">Vanalinn</option>" +
					"</select> Linnaosa <br />" +
					"<input type=\"k\" name=\"k\" /> Neighbor Count (k) <br />" +
					"<input type=\"submit\" value=\"Submit\" />" +
			"</form>" +
			"</html>";
	
	
  public void handle(HttpExchange exchange) throws IOException {
	  
    String requestMethod = exchange.getRequestMethod();
    if (requestMethod.equalsIgnoreCase("GET")) {
      Headers responseHeaders = exchange.getResponseHeaders();
      responseHeaders.set("Content-Type", "text/html");
      exchange.sendResponseHeaders(200, 0);

      OutputStream responseBody = exchange.getResponseBody();
      Headers requestHeaders = exchange.getRequestHeaders();
      Set<String> keySet = requestHeaders.keySet();
      Iterator<String> iter = keySet.iterator();
      
        responseBody.write(html.getBytes("UTF-8"));
      
      responseBody.close();
    }
  }
}